package fido;


import org.apache.log4j.Logger;
import org.mymediadb.api.mmdb.api.MmdbApi;
import org.mymediadb.api.mmdb.internal.api.MmdbApiImpl;
import org.mymediadb.api.mmdb.model.Media;
import org.mymediadb.api.mmdb.model.Movie;
import org.mymediadb.api.mmdb.model.User;
import org.mymediadb.api.mmdb.model.UserMedia;

import javax.security.auth.login.LoginException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;


public final class MmdbUtils {
    private static final Logger LOG = Logger.getLogger(MmdbUtils.class);
    private static String username;
    private static String password;
    private static final MmdbApi MMDB_API;

    static {
        MMDB_API = MmdbApiImpl.getInstance();

    }

    private MmdbUtils() {
        //Private constructor
    }

    public static void setUsername(String newUsername) {
        username = newUsername;
    }

    public static void setPassword(String newPassword) {
        password = newPassword;
    }

    public static User loginUser() throws LoginException {
        MMDB_API.setBasicAuthentication(username, password);
        User user = MMDB_API.getUser();
        if (user == null) {
            throw new LoginException("Wrong username/password");

        }
        return user;
    }


    public static List<Movie> getWishlistedMovies(User user) {
        List<Movie> wishlistedMovies = new ArrayList<Movie>();
        Collection<? extends Media> library = user.getMediaLibrary();
        System.out.println("Counting movies:");
        for (Media m : library) {
            //System.out.print("*");
            long id = m.getMediaId();
            Movie movie = MMDB_API.getMedia(Movie.class, MmdbApi.IdType.MMDB, id);
            if (movie.getUserMedia().isWishlisted()) {
                wishlistedMovies.add(movie);
            }

        }
        return wishlistedMovies;
    }

    public static List<Movie> getWishlistedMovies() throws LoginException {
        username = FidoCommonUtils.getPropertyValue("fido.mmdb.username");
        password = FidoCommonUtils.getPropertyValue("fido.mmdb.password");
        if (username.equals("") || password.equals("")) {
            LOG.info("Missing username/password to MyMediaDb.org,  please run: fido -install");
            System.exit(-1);

        }
        return getWishlistedMovies(loginUser());
    }


    public static void setMovieAsAcquired(Movie movie) {
        // MmdbApi MMDB_API = MmdbApiImpl.getInstance();
        // MMDB_API.setBasicAuthentication(username, password);
        // User user = MMDB_API.getUser();
        UserMedia userMedia = MMDB_API.getEmptyUserMedia();
        userMedia.setAcquired(true);
        MMDB_API.putUserMedia(MmdbApi.MediaType.MOVIE, MmdbApi.IdType.MMDB, movie.getMediaId(), userMedia);


    }


}
